//
//  HomeViewController.swift
//  Status
//
//  Created by 花轮 on 15/5/10.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit

class HomeViewController: BaseViewController, StatusCellDelegate {
    @IBOutlet weak var titleButton: HomeTitleButton!
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        visitorView?.setupInfo("visitordiscover_feed_image_house", descText: "😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄", isHome: true)
        
    }
    
    var rowHeightCache = NSCache()

    
    var statuses:[Status]?{
        didSet{
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setupTitleButton()
        
        if userLogin{
        loadData()
        }
    }
    
    private func loadData()
    {
        Status.loadStatus { (statuses) -> () in
            self.statuses = statuses
        }
    }
    //MARK: - tableView的数据源和代理方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellReuseID(status)) as! StatusCell
        cell.status = status
        cell.imgDelegate = self
        return cell
    }
    
    func statusCellDidSelectedImg(cell: StatusCell, index: Int) {
//        println("\(cell) \(index)")
        
        let browser = ImgBrowserViewController()
        
        browser.imageURLs = cell.status?.largePicURLs
        
        // 设置modal转场代理
        browser.transitioningDelegate = self
        // 设置modal的类型
        browser.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(browser, animated: true, completion: nil)
    }
    
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//        println(__FUNCTION__)
        return 300
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        println(__FUNCTION__)
        
        let status = statuses![indexPath.row]
        
        // 判断是否已经缓存了行高
        if rowHeightCache.objectForKey(status.id) != nil{
            let r = rowHeightCache.objectForKey(status.id) as! CGFloat
            
//            println("rrrrrrr \(r)")
            
            return r
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellReuseID(status)) as! StatusCell
        
        let height = cell.rowHeight(status)
        
        rowHeightCache.setObject(height, forKey: status.id)
        
        return height
    }
    
    // MARK: -
    @IBAction func qrcodeClick(sender:UIButton)
    {
        presentViewController(UIStoryboard.initialViewController("QRCode"), animated: true, completion: nil)
    }
        func setupTitleButton()
    {
        if sharedUserAccount != nil
        {
            titleButton.setTitle(sharedUserAccount!.name, forState: UIControlState.Normal)
        }
        else
        {
            titleButton.setTitle("首页", forState: UIControlState.Normal)
        }
    }
    
    let animaterDelegate = PopoverAnimater()
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // 做跳转连接中的准备工作
        if segue.identifier == "Home2Popover"
        {
            let popVc = segue.destinationViewController as! PopoverViewController
            
            
            /* 要实现自定义转场
            // 1. 设置转场代理
                返回 UIPresentationController，由该控制器，负责modal界面的处理
            // 2. 指定modal的展现方式是自定义

            */
            
            // transition 从一个界面跳到另一个界面
            popVc.transitioningDelegate = animaterDelegate
            
            // 设置展现的大小
            let x = (self.view.bounds.width - 200) * 0.5
            animaterDelegate.presentedFrame = CGRectMake(x, 56, 200, 240)
            
            animaterDelegate.titleBtn = titleButton
            
            // 设置展现方式
            popVc.modalPresentationStyle = UIModalPresentationStyle.Custom
        }
    }
}


// 指定转场动画的执行
extension HomeViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if let toView = transitionContext.viewForKey(UITransitionContextToViewKey){
            transitionContext.containerView().addSubview(toView)
            
            toView.frame = CGRectMake(0, 0, 0, 0)
            toView.alpha = 0
            
            UIView.animateWithDuration(2.0, animations: { () -> Void in
                toView.frame = UIScreen.mainScreen().bounds
                toView.alpha = 1.0
            }, completion: { (_) -> Void in
                transitionContext.completeTransition(true)
            })
            
        }
    }
}